<template>
  <div class="goods">
    <div class="goods-content">
      <div class="meta">
        <div class="goods-img">
          <el-carousel trigger="click" height="428px">
            <el-carousel-item v-for="(item, index) in goodsData.detailData.goodsImg?.split(',')" :key="index">
              <img :src="item" />
            </el-carousel-item>
          </el-carousel>

          <div class="tip">
            <span>温馨提示</span>
            <p>图片均为对原品的真实拍摄，仅供参考;如遇新包装上市可能存在更新滞后，请以实物为准!</p>
          </div>
        </div>
        <div class="goods-detail">
          <div class="goods-name">
            {{ goodsData.detailData.goodsName }}
          </div>
          <div class="goods-sub" v-if="goodsData.detailData.goodsSubtitle">{{ goodsData.detailData.goodsSubtitle }}</div>
          <div class="goods-price">
            <span class="goods-title">售价</span>
            <div>
              <span class="goods-content">￥</span>
              <span class="goods-price-value">{{ goodsData.detailData.goodsSalesPrice?.toFixed(2) }}</span>
            </div>
          </div>
          <div style="margin: 20px 0 0 10px">
            <div class="goods-cate">
              <span class="goods-title">器械类别</span>
              <span class="goods-content">{{ goodsData.detailData?.apparatusCategory?.apparatusCategoryName }}</span>
            </div>
            <div class="goods-factory" v-if="goodsData.detailData.factoryName">
              <span class="goods-title">生产厂家</span>
              <span class="goods-content">{{ goodsData.detailData.factoryName }}</span>
            </div>
            <div class="goods-spec">
              <template v-for="item in goodsData.detailData.goodsExpandparamValueList" :key="item.expandparamValueId">
                <div class="expand">
                  <span class="goods-title">{{ item.expandparamName }}</span>
                  <span class="goods-content">{{ item.expandparamValueName }}</span>
                </div>
              </template>
            </div>
            <div class="goods-num">
              <span class="goods-title">数量</span>
              <el-input-number class="goods-content" size="small"  v-model="goodsData.addCartForm.amount" @change="onAmountChange" />
            </div>

            <div class="goods-btn">
              <Button v-if="goodsData.detailData.salesFlag === 'NO'" class="goods-disable-buy" disabled label="暂无购买权限" />
              <div v-else>
                <Button class="goods-buy" label="立即购买" @click="onCartPurchaseClick" :disabled="goodsData.detailData.stock === 0 || goodsData.detailData.salesFlag === 'NO'" />
                <Button class="goods-add" label="加入购物车" :style="{ background: goodsData.detailData.stock === 0 || goodsData.detailData.salesFlag === 'NO' ? '#ccc' : '#e89000' }"
                        :disabled="goodsData.detailData.stock === 0 || goodsData.detailData.salesFlag === 'NO'" @click="onAddShoppingCart" />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="detail">
        <div class="goods-detail-img">
          <el-tabs type="card" class="goods-tabs">
            <el-tab-pane label="商品详情">
              <div v-if="goodsData.instructions?.length > 0" class="qualica-img">
                <img v-for="(item, index) in goodsData.instructions" :key="index" :src="item" />
              </div>

              <div v-if="goodsData.goodsDetailImg?.length > 0" class="goods-img">
                <img v-for="(item, index) in goodsData.goodsDetailImg" :key="index" :src="item" />
              </div>

              <div v-if="goodsData.detailData?.goodsQualificationList?.length > 0" class="qualica-img">
                <!--                <img v-for="item in goodsData.detailData.goodsQualificationList.qualificationListImg"  :src="item.url" />-->
                <div v-for="item in goodsData.detailData.goodsQualificationList">
                  <img v-for="srcItem in item.qualificationListImg"  :src="srcItem.url" />
                </div>
              </div>

              <div v-else>
                <el-empty description="暂无数据" />
              </div>
            </el-tab-pane>
            <el-tab-pane label="产品信息">
              <ul class="goods-spec">
                <li v-for="(item, index) in goodsData.goodsIntro" :key="index">
                  <span v-if="item.title === '有效期'" class="title">{{ `${item.title}（月）` }} </span>
                  <span v-else class="title">{{ item.title }}</span>

                  <el-image v-if="item.title === '产品组成' && isShow" class="img" :src="item.value" :preview-src-list="[item.value]" />

                  <span v-else>{{ item.value || '' }}</span>
                </li>
              </ul>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="store">
          <div class="store-title">
            <img src="@/assets/images/dianpu.png" />
            <el-tooltip class="box-item" effect="dark" :content="goodsData.detailData.supplierName" placement="bottom-start">
              <span class="store-name">{{ goodsData.detailData.supplierName }}</span>
            </el-tooltip>

            <Button label="进入" class="enter-btn" @click="onEnterClick" />
          </div>
          <div class="other-goods">
            <p class="other-goods-title"><span>其他产品</span></p>
            <ul class="store-goods-value">
              <li v-for="item in goodsData.otherData" :key="item.goodsId" @click="onGoodsClick(item.goodsId)">
                <img :src="item.goodsImg?.split(',')[0]" />
                <div class="info">
                  <p class="other-goods-name">{{ item.goodsName }}</p>
                  <p class="other-goods-sub">{{ item.goodsSubtitle }}</p>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import api from '@/api'
import { cartStore } from '@/store/cart'
import { SupplierStore } from '@/store/supplier'
import Button from '@/components/button/button.vue'

const route = useRoute()
const router = useRouter()
const _cartStore = cartStore()
const _supplierStore = SupplierStore()

const customerId = localStorage.getItem('_site_login_userId')

const goodsData = reactive({
  detailData: {},
  goodsIntro: [
    {
      title: '产品名称',
      name: 'productName'
    },
    {
      title: '销售单位',
      name: 'packingUnit'
    },

    {
      title: '生产企业',
      name: 'productionEnterprise'
    },
    {
      title: '注册人',
      name: 'registrant'
    },
    {
      title: '注册证号',
      name: 'registrationNumber'
    },
    {
      title: '有效期',
      name: 'validityPeriod'
    },
    {
      title: '使用方法',
      name: 'methodApplication'
    },
    {
      title: '适用范围',
      name: 'applicationScope'
    },
    {
      title: '禁忌症',
      name: 'contraindication'
    },
    {
      title: '产品组成',
      name: 'productFormation'
    }
  ],
  otherData: [],
  goodsSalesPrice: 0,
  addCartForm: {
    amount: 1
  },
  currSpec: {},
  goodsDetailImg: '',
  instructions: ''
})

const isShow = ref(false)
const expend = ref(false)
const error = ref(false)



const addCart = async () => {
  if (goodsData.addCartForm.amount < goodsData.detailData.minimumQuantity) {
    nextTick(() => {
      goodsData.addCartForm.amount = goodsData.detailData.minimumQuantity
    })
    ElMessage.error(`此商品起订量为${goodsData.detailData.minimumQuantity}，请重新输入商品数量`)
      return
  }
  let { factoryName, goodsDesc, goodsId, goodsImg, goodsName, goodsSubtitle, supplierId, unit, goodsSalesPrice, goodsCatNameFirst, goodsCatNameSecond } = goodsData.detailData

  goodsData.addCartForm.goodsCategoryName = goodsCatNameFirst + '-' + goodsCatNameSecond

  goodsData.addCartForm.price = goodsSalesPrice
  goodsData.addCartForm = Object.assign(goodsData.addCartForm, { factoryName, goodsDesc, goodsId, goodsImg, goodsName, goodsSubtitle, supplierId, unit })
  goodsData.addCartForm.goodsImg = goodsImg?.split(',')[0]

  let { err } = await api.post(`/medinstrument/site/cart/addCart`, goodsData.addCartForm)
  if (err) {
    ElMessage.error(err)
  } else {
    _cartStore.add(goodsId)
    ElMessage.success('商品添加成功')
  }
}

const loadData = async () => {
  let { data, err } = await api.get(`/medinstrument/site/goods/goodsDetail?goodsId=${route.params.id}`)
  if (err) {
    error.value = err
    router.push('/goods/notFound')
    return
  } else {
    goodsData.detailData = data.goodsVo
    goodsData.detailData.goodsQualificationList.forEach(item => {
      item.qualificationListImg = item.qualificationImg.includes(',') ? item.qualificationImg.split(',').map((e) => ({
        url: e,
        old: true
      })) : [item.qualificationImg].map((e) => ({
        url: e,
        old: true
      }))
    })
    document.title = goodsData.detailData.goodsName
    const isImage = computed(() => {
      let reg = /(\.jpg|\.jpeg|\.png)$/i

      return reg.test(goodsData.detailData.goodsIntro.productFormation)
    })
    goodsData.addCartForm.amount = goodsData.detailData.minimumQuantity
    isImage.value ? (isShow.value = true) : (isShow.value = false)
    goodsData.otherData = data.otherGoods
    goodsData.goodsIntro?.forEach((e) => {
      e.value = data.goodsVo.goodsIntro?.[e.name]
    })
    goodsData.addCartForm.amount = goodsData.detailData.minimumQuantity

    _supplierStore.setName(goodsData.detailData.supplierName)
    _supplierStore.setId(goodsData.detailData.supplierId)

    try {
      goodsData.goodsDetailImg = JSON.parse(data.goodsVo.goodsDetail.split(','))
      goodsData.instructions = JSON.parse(data.goodsVo.instructions.split(','))
    } catch (error) {}

    if (goodsData.detailData.stock === 0 || goodsData.detailData.stock === null) {
      ElMessage.warning('商品无库存!')
      return
    }
  }
}

const onAddShoppingCart = () => {
  addCart()
}

const onCartPurchaseClick = () => {
  if (goodsData.addCartForm.amount < goodsData.detailData.minimumQuantity) {
    nextTick(() => {
      goodsData.addCartForm.amount = goodsData.detailData.minimumQuantity
    })
    ElMessage.error(`此商品起订量为${goodsData.detailData.minimumQuantity}，请重新输入商品数量`)
    return
  }
  router.push({ path: '/settlement', query: { amount: goodsData.addCartForm.amount, goodsId: route.params.id } })
}

const onEnterClick = () => {
  let { href } = router.resolve({
    path: '/store',
    query: { supplierId: goodsData.detailData.supplierId }
  })
  window.open(href, '_blank')
}

const onGoodsClick = (goodsId) => {
  let { href } = router.resolve({
    path: `/goods/${goodsId}`
  })
  window.open(href, '_blank')
}

const onAmountChange = (val) => {
  // TODO 商品数量默认数值为商品起订量，当输入起订量以下的数值后弹窗提示“此商品起订量为xxx，请重新输入商品数量”
  if (goodsData.addCartForm.amount < goodsData.detailData.minimumQuantity) {
    ElMessage.error(`此商品起订量为${goodsData.detailData.minimumQuantity}，请重新输入商品数量`)
  }
}
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.goods {
  min-height: 393px;

  .goods-content {
    width: 1080px;
    margin: 0 auto;
    overflow-y: auto;

    .meta {
      display: flex;
      justify-content: space-between;
      padding-top: 10px;

      .goods-img {
        img {
          box-sizing: border-box;
          width: 428px;
          height: 428px;
          border: 1px solid var(--border-color);
          box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);
        }

        .tip {
          display: flex;
          width: 428px;
          margin-top: 20px;
          font-size: 12px;
          color: #606266;
          line-height: 17px;

          span {
            display: inline-block;
            width: 48px;
            height: 17px;
            color: var(--color-primary);
            margin-right: 12px;
          }

          p {
            width: 368px;
          }
        }
      }

      .goods-detail {
        width: 612px;
        margin-left: 40px;
        color: var(--color-text);

        .goods-name {
          font-size: 16px;
          color: var(--color-text);
          font-weight: 500;
        }

        .goods-sub {
          margin: 8px 0 20px 0;
          color: var(--color-primary);
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .goods-title {
          display: inline-block;
          font-size: 12px;
          color: var(--color-text);
          width: 58px;
        }

        .goods-price,
        .goods-cate,
        .goods-brand,
        .goods-factory,
        .goods-spec,
        .goods-num {
          margin-bottom: 20px;
          .goods-content {
            margin-left: 30px;
          }
        }

        .goods-price {
          display: flex;
          align-items: center;
          padding: 14px 0 14px 10px;
          background: var(--color-background);
          box-sizing: border-box;

          .goods-content,
          .goods-price-value {
            color: #c00000;
          }

          .goods-price-value {
            font-size: 24px;
            line-height: 33px;
            font-weight: 500;
          }
        }

        .goods-spec {
          .expand {
            margin-bottom: 20px;
          }

          .expand:last-child {
            margin-bottom: 0;
          }
        }

        .goods-num {
          display: flex;
          align-items: center;
        }

        .goods-num .el-input-number :deep(.el-input--small) {
          width: 124px;
          height: 34px;
        }

        .el-input-number--small {
          width: 124px;

          :deep(.el-input-number__decrease),
          :deep(.el-input-number__increase) {
            width: 32px;
            height: 32px;
            box-sizing: border-box;
          }
        }

        :deep(.goods-add),
        :deep(.goods-buy),
        :deep(.goods-disable-buy) {
          width: 158px;
          height: 52px;
          border-radius: 2px;
          margin-top: 20px;
          font-size: 22px;
        }

        :deep(.goods-add) {
          background-color: var(--color-primary);
          margin-left: 20px;
          border: none;

          span {
            color: #ffffff;
          }
        }

        :deep(.goods-buy) {
          background-color: #fff9ee;
          border: 1px solid rgba(232, 144, 0, 1);

          span {
            color: var(--color-primary);
          }
        }

        :deep(.goods-disable-buy) {
          background-color: #f5f7fa;
          color: #c0c4cc;
        }
      }
    }

    .detail {
      display: flex;
      justify-content: space-between;
      margin-top: 80px;

      .goods-img,
      .qualica-img {
        margin-top: 10px;
        width: 760px;

        img {
          width: 100%;
        }
      }

      .goods-spec {
        width: 760px;

        li {
          display: flex;
          align-items: center;
          box-sizing: border-box;
          padding: 20px;
          border-bottom: 1px solid var(--border-color);
          color: #606266;
          font-size: 12px;

          .title {
            display: inline-block;
            width: 80px;
          }

          span:last-child {
            display: inline-block;
            margin-left: 60px;
            flex: 1;
          }

          .img {
            width: 146px;
            height: 146px;
            margin-left: 60px;
          }
        }
      }

      .store {
        width: 264px;

        .store-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-bottom: 10px;
          border-bottom: 1px solid #ededed;

          img {
            width: 32px;
            height: 32px;
          }

          .store-name {
            max-width: 154px;
            height: 20px;
            line-height: 20px;
            text-overflow: -o-ellipsis-lastline;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .enter-btn {
            width: 48px;
            height: 30px;
            background-color: var(--color-primary);
            border-radius: 2px;
            color: #fff;
            border: 0;
          }
        }

        .other-goods {
          .other-goods-title {
            display: flex;
            justify-content: center;
            margin: 20px 0;
            font-size: 16px;

            span {
              display: flex;
              align-items: center;
            }
            span:before,
            span:after {
              content: '';
              display: block;
              width: 18px;
              height: 1px;
              background-color: var(--color-text);
            }

            span:before {
              margin-right: 10px;
            }

            span:after {
              margin-left: 10px;
            }
          }
        }

        .store-goods-title {
          font-size: 16px;
          color: var(--color-text);
          text-align: center;
          padding: 20px;
        }

        .store-goods-value {
          li {
            width: 264px;
            background-color: #fff;
            display: inline-block;
            margin-right: 10px;
            margin-bottom: 10px;
            border: 1px solid rgba(228, 231, 237, 1);
            box-sizing: border-box;
            cursor: pointer;

            &:hover {
              border: 1px solid #f2a103;
            }

            img {
              width: 100%;
              height: 250px;
            }

            .info {
              display: flex;
              flex-direction: column;
              padding: 10px 10px 20px;
              box-sizing: border-box;

              .other-goods-name,
              .other-goods-sub {
                width: 244px;
                overflow: hidden;
                text-overflow: ellipsis;
              }

              .other-goods-name {
                font-size: 16px;
                font-weight: 500;
                text-overflow: -o-ellipsis-lastline;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
              }

              .other-goods-sub {
                white-space: nowrap;
                margin-top: 8px;
                color: var(--color-primary);
              }
            }
          }
        }
      }
    }
  }
}

.arrowTransform {
  position: absolute;
  right: 30px;
  transition: 0.2s;
  transform-origin: center;
  transform: rotateZ(180deg);
}

.arrowTransformReturn {
  position: absolute;
  right: 30px;
  transition: 0.2s;
  transform-origin: center;
  transform: rotateZ(0deg);
}
</style>
<style>
.el-input-number--small .el-input-number__increase .el-icon,
.el-input-number--small .el-input-number__decrease .el-icon {
  font-size: 17px;
}

.el-input-number--small .el-input-number__increase:hover,
.el-input-number--small .el-input-number__decrease:hover,
.el-input-number--small .el-input-number__increase .el-icon:hover,
.el-input-number--small .el-input-number__decrease .el-icon:hover {
  color: var(--color-primary);
}

.detail .el-tabs .el-tabs__header {
  box-sizing: border-box;
  width: 760px;
  height: 42px;
  background: #f9f9f9;
  border-bottom: 1px solid #16bfa7;
  margin: 0;
}

.detail .el-tabs .el-tabs__header .el-tabs__item:hover {
  color: var(--color-text);
}

.detail .el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
  background: #64c8b9;
  color: #fff;
}

.detail .el-tabs--card > .el-tabs__header .el-tabs__item {
  border-bottom: 0;
}
</style>
